import { reqAddcart, reqCartList, reqchangeChecked, reqRemoveSku } from "@/api";

const state = {
  cartList: [],
};
const mutations = {
  GETCARTLIST(state, data) {
    state.cartList = data;
  },
};
const actions = {
  async getcartlist({ state, commit, dispatch }) {
    let res = await reqCartList();
    if (res.code === 200) {
      commit("GETCARTLIST", res.data);
    }
  },

  async addOneFun({ state, commit, dispatch }, { skuId, skuNum }) {
    let res = await reqAddcart({ skuId, skuNum });
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async minusOneFun({ state, commit, dispatch }, { skuId, skuNum }) {
    let res = await reqAddcart({ skuId, skuNum });
    if (res.code === 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async changeskuNumFun({ state, commit, dispatch }, { skuId, skuNum }) {
    let res = await reqAddcart({ skuId, skuNum });
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async removeSkuFun({ state, commit, dispatch }, skuId) {
    let res = await reqRemoveSku(skuId);
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  async changeCheckedFun({ state, commit, dispatch }, { skuId, isChecked }) {
    let res = await reqchangeChecked({ skuId, isChecked });
    if (res.code == 200) {
      return "ok";
    } else {
      return Promise.reject();
    }
  },
  allChangeFun({ state, commit, dispatch }, isChecked) {
    let arr = [];
    state.cartList[0].cartInfoList.forEach((item) => {
      let res = dispatch("changeCheckedFun", { skuId: item.skuId, isChecked });
      arr.push(res);
    });
    return Promise.all(arr);
  },
  allRemoveSkuFun({ state, commit, dispatch }) {
    let arr = [];
    state.cartList[0].cartInfoList.forEach((item) => {
      if (item.isChecked == 1) {
        let res = dispatch("removeSkuFun", item.skuId);
        arr.push(res);
      }
    });
    return Promise.all(arr);
  },
};
const getters = {
  info(state) {
    return state.cartList[0] || {};
  },
  good(state, getters) {
    return getters.info.cartInfoList || [];
  },
};

export default { namespaced: true, state, mutations, actions, getters };
